Skip to main content

Resource Limits

Piscina allows you to set resource limits on worker threads to prevent them from consuming excessive memory. The example below will show you how to configure and use resource limits to handle out-of-memory scenarios.

The main file sets up a Piscina instance with specific resource limits:

  • maxOldGenerationSizeMb: Limits the maximum size of the old generation in the V8 heap to 16 MB.
  • maxYoungGenerationSizeMb: Limits the maximum size of the young generation in the V8 heap to 4 MB.
  • codeRangeSizeMb: Limits the size of the code range to 16 MB.
index.js
'use strict';

const Piscina = require('piscina');
const { resolve } = require('path');
const { strictEqual } = require('assert');

const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js'),
resourceLimits: {
maxOldGenerationSizeMb: 16,
maxYoungGenerationSizeMb: 4,
codeRangeSizeMb: 16
}
});

(async function () {
try {
await piscina.run();
} catch (err) {
console.log('Worker terminated due to resource limits');
strictEqual(err.code, 'ERR_WORKER_OUT_OF_MEMORY');
}
})();

The worker file contains a function that deliberately causes a memory leak by creating an infinitely growing array. This will eventually exceed the memory limits set in the main file.

worker.js
'use strict';

module.exports = () => {
const array = [];
while (true) {
array.push([array]);
}
};

You can also check out this example on github.